import { useState, useMemo, useLayoutEffect, useRef } from 'react';
import produce from 'immer';

function switchColumnFn(data, key, keyNo1Value, keyNo2Value) {
    return produce(data, draftData => {
        let no1Index = draftData.findIndex((v) => v[key] === keyNo1Value);
        let no2Index = draftData.findIndex((v) => v[key] === keyNo2Value);
        if (no1Index > -1 && no2Index > -1) {
            let no1Data = draftData[no1Index];
            let no2Data = draftData[no2Index];
            draftData[no2Index] = no1Data;
            draftData[no1Index] = no2Data;
        }
    })
}
function changeColumnFn(data, key, column) {
    return produce(data, draftData => {
        let columnIndex = draftData.findIndex((v) => v[key] === column[key]);
        if (columnIndex > -1) {
            draftData[columnIndex] = { ...draftData[columnIndex], ...column }
        }
    })
}

const getModifyColumns = setFn => (params) => {
    const { operate, column } = params;
    if (operate === 'switch') {
        let { keyNo1Value, keyNo2Value } = params;
        setFn(crtState => {
            return switchColumnFn(crtState, 'key', keyNo1Value, keyNo2Value);
        })
    }
    if (operate === 'change') {
        setFn(crtState => {
            return changeColumnFn(crtState, 'key', column);
        })
    }
}


/**
 * 
 * @param {Array} originalColumns 原始columns
 * @param {Number} mainWidth main部分的宽度
 * @returns 
 */
function useProcColumns(originalColumns, mainWidth) {
    const [columns, setColumns] = useState([]);
    const [leftColumns, setLeftColumns] = useState([]);
    const [rightColumns, setRightColumns] = useState([]);
    const cashRef = useRef({}); // main部分的column宽度总和  有最小宽度属性的个数

    const modifyColumns = useMemo(() => getModifyColumns(setColumns), []);
    const modifyLeftColumns = useMemo(() => getModifyColumns(setLeftColumns), []);
    const modifyRightColumns = useMemo(() => getModifyColumns(setRightColumns), []);

    useLayoutEffect(() => {
        const _leftColumns = [], _rightColumns = [], _columns = [];
        let columnsWidth = 0, // main部分column宽度总和
            hasMinWidthLen = 0; // 有最小宽度属性的个数
        originalColumns.forEach(item => {
            if (item.freeze) {
                if (item.orientation === 'left') _leftColumns.push(item);
                else if (item.orientation === 'right') _rightColumns.push(item);
            }
            else {
                columnsWidth += item.minWidth || item.width || 100;
                if (item.minWidth) {
                    hasMinWidthLen++;
                }
                _columns.push({ ...item, width: item.minWidth ? item.minWidth : (item.width || 100) });
            }
        });
        cashRef.current = { columnsWidth, hasMinWidthLen };
        setLeftColumns(_leftColumns);
        setRightColumns(_rightColumns);
        setColumns(_columns)
    }, [originalColumns]);

    useLayoutEffect(() => {
        if (!mainWidth) return;
        const { columnsWidth, hasMinWidthLen, isMin } = cashRef.current;
        if (hasMinWidthLen) {
            if (columnsWidth < mainWidth) {
                cashRef.current.isMin = false;
                const leftW = mainWidth - columnsWidth; // 剩余可分配宽度
                const diffW = Math.floor(leftW / hasMinWidthLen); // 每列分配宽度
                const resetW = Math.floor(leftW - diffW * hasMinWidthLen);
                setColumns(_columns => _columns.map((item, i) => ({
                    ...item,
                    width: (item.minWidth ? item.minWidth + diffW : item.width) + (i === 0 ? resetW : 0),
                })));
            }
            else {
                if (isMin) return; // 上次已经是最小的这次就不用更新了
                cashRef.current.isMin = true;
                setColumns(_columns => _columns.map(item => ({
                    ...item,
                    width: item.minWidth ? item.minWidth : item.width,
                })));
            }
        }
    }, [mainWidth]);

    return { columns, leftColumns, rightColumns, modifyColumns, modifyLeftColumns, modifyRightColumns }
}
export default useProcColumns;